/**
 * 商品分类页面
 */
import originCategories from "../../mock/goodsRecommend";

Page({
  data: {
    categories: [],
    currentGoods: [],
    activeCategoryName: '',
    cartItems: [],
    category: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取所有分类
    const categories = [...new Set(originCategories.map((item) => item.category))];
    
    // 首先尝试从URL参数获取分类
    let activeCategoryName = options.category;
    
    // 如果URL中没有分类参数，则尝试从全局数据获取目标分类
    if (!activeCategoryName) {
      const app = getApp();
      activeCategoryName = app.globalData.targetCategory;
      
      // 清除全局数据，避免重复使用
      app.globalData.targetCategory = null;
    }
    
    // 如果都没有指定分类，默认使用第一个分类
    if (!activeCategoryName || !categories.includes(activeCategoryName)) {
      activeCategoryName = categories[0];
    }
    
    this.setData({
      categories,
      activeCategoryName,
      currentGoods: originCategories.filter(
        (item) => item.category === activeCategoryName
      ),
    }); 
    
    // 初始化时同步购物车数据
    this.syncCartData();
  },
  
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 当页面从tab切换显示时，检查是否需要更新分类
    const app = getApp();
    if (app.globalData.targetCategory) {
      const categories = [...new Set(originCategories.map((item) => item.category))];
      let activeCategoryName = app.globalData.targetCategory;
      
      // 检查分类是否有效
      if (categories.includes(activeCategoryName)) {
        this.setData({
          activeCategoryName,
          currentGoods: originCategories.filter(
            (item) => item.category === activeCategoryName
          ),
        });
      }
      
      // 清除全局数据，避免重复使用
      app.globalData.targetCategory = null;
    }
    
    // 每次页面显示时同步购物车数据
    this.syncCartData();
  },

  /**
   * 同步购物车数据
   */
  syncCartData() {
    const app = getApp();
    const cartItems = app.globalData.cartItems || [];
    const cartCount = cartItems.reduce((total, item) => total + (item.count || 0), 0);
    
    console.log('同步购物车数据:', cartItems, '数量:', cartCount); // 调试用
    
    this.setData({
      cartItems: cartItems,
      cartCount: cartCount
    });
  },

  /**
   * 点击分类跳转对应分类
   */
  tapCategory(e) {
    const activeCategoryName = e.currentTarget.dataset.category; 
    this.setData({
      activeCategoryName,
      currentGoods: originCategories.filter(
        (item) => item.category === activeCategoryName
      )
    });
  },

  /**
   * 加入购物车
   */
  tapAdd(e){
    const itemId = e.currentTarget.dataset.id;
    const item = this.data.currentGoods.find(good => good.id === itemId);
    if (item) {
      const app = getApp();
      let cartItems = app.globalData.cartItems || [];
      
      const existingItemIndex = cartItems.findIndex(cartItem => cartItem.id === itemId);
      if (existingItemIndex !== -1) {
        cartItems[existingItemIndex].count += 1;
      } else {
        cartItems.push({ ...item, count: 1 });
      }
      
      // 更新全局数据
      app.globalData.cartItems = cartItems;
      app.globalData.cartCount = cartItems.reduce((total, item) => total + item.count, 0);
      
      // 更新页面数据
      const cartCount = app.globalData.cartCount;
      this.setData({
        cartItems: cartItems,
        cartCount: cartCount
      });
      
      wx.showToast({
        title: '已加入购物车',
        icon: 'success',
      });
    }
  },
  
  /**
   * 跳转到购物车页面
   */
  navigateToCart() {
    wx.navigateTo({
      url: '/pages/cart/index',
    });
  }
});